﻿using biaoqian;
using FastReport;
using FastReport.Editor;
using FastReport.Web;
using FastReport.Export;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.DynamicData;
using System.Web.Mvc;
using FastReport.Web.Handlers;
using System.Globalization;

namespace Wkol.Controllers
{
    public class DyinController : Controller
    {
        Class1 one = new Class1();

        // GET: Dyin
        public ActionResult Index(string comdj, string shulian, int stace = 0, string bianma = "" ,string JINS="")
        {
            if (stace == 1)
            {
              //var  path = "..\\Fastreport\\ProductAntiFake.frx";
                DataTable dataTable2 = NewM(comdj, ref shulian, JINS);
            }

            if (stace == 2)
            {
                DataTable dataTable1 = one.Wuliao();
                DataTable dataTable2 = NewM(comdj, ref shulian, JINS);//返回需要打印的标签信息
                                                         //------------------------------------------------------------
                List<List<object>> BiasoR = NewMethod();//返回物料的对饮大小标签
                var FE = BiasoR[0][0].ToString();
                var FES = BiasoR[1][0].ToString();
                var path = "";//打开的标签
                              //再分辨物料的大小标签
                path = biaoqinazhi(dataTable2, FE, FES, path);
                if (path == "")
                {
                    return Content("<script>history.go(-1); alert('该行不是眼睛标签打印项');</script>");
                }
                var skol = path == "~/Fastreport/ProductBoxA.frx" ? "A" : path == "~/Fastreport/ProductBoxB.frx" ? "B" : null;
                ViewBag.JINF = skol;
                dataTable1 = Wuliaos(dataTable2);//返回的数据
                DataRow rows = dataTable1.Rows[0];
                DataRow row = dataTable2.Rows[0];
                var ling = Convert.ToInt16(rows["QTY"]);
                int sdk;
                string s = row["quantity"].ToString();
                int d = s == "" ? 1 : Convert.ToInt16(row["quantity"]);
                sdk = ling == 0 ? 0 : d / Convert.ToInt16(rows["QTY"]);
                rows["COUNTRY_ORIGIN_DW"] = sdk;
                
                //考虑物料不止一个
                for (int i = 0; i < dataTable1.Rows.Count; i++)
                {
                    path = Server.MapPath(path);
                    DataSet da = new DataSet();
                    da.Tables.Add(dataTable1);
                    dataTable1.TableName = "Table1";
                    WebReport webReport = new WebReport();
                    webReport.Report.Load(path);//打开文件/*
                    webReport.RegisterData(da);//绑定数据源
                                               //webReport.Report.SetParameterValue("ksnfjidn", Appbian);//替换fastreport参数的值--
                    DataBand data = webReport.Report.FindObject("Data1") as DataBand;
                    data.DataSource = webReport.Report.GetDataSource("Table1");
                    webReport.Height = 500;
                    webReport.Width = 1000;
                    ViewBag.WebReport = webReport;
                    da.Tables.Clear();
                }
                //防伪码
                path = "..\\Fastreport\\ProductAntiFake.frx";
                //数据源
                path = Server.MapPath(path);
                DataSet daw = new DataSet();
                daw.Tables.Add(dataTable1);
                dataTable1.TableName = "Table1";
                WebReport webReport1 = new WebReport();
                webReport1.Report.Load(path);//打开文件/*
                webReport1.RegisterData(daw);//绑定数据源
                                             //webReport.Report.SetParameterValue("ksnfjidn", Appbian);//替换fastreport参数的值--
                DataBand dataws = webReport1.Report.FindObject("Data1") as DataBand;
                dataws.DataSource = webReport1.Report.GetDataSource("Table1");
                webReport1.Height = 500;
                webReport1.Width = 1000;
                ViewBag.WebReports = webReport1;
            }
            return View();
        }
        //查询发货通知单
        private DataTable NewM(string comdj, ref string shulian,string shinf)
        {
            //根据单号查找物料并返回
            K3CloudApi client1 = new K3CloudApi();
            //业务对象标识
            string formId1 = "SAL_DELIVERYNOTICE";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys1 = "FBillNo,FCustomerID.FName,FMaterialID.FNumber,FMaterialName,FMateriaModel,FQty,FPriceUnitId.FName,F_SMGS_FHDate,FSaleOrgId.FName";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
            var ZBLxsx = comdj;
            var paramed = new QueryParam()
            {
                FormId = formId1,
                FieldKeys = fieldKeys1,
                FilterString = "FBillNo like'%" + ZBLxsx + "%' and FSaleOrgId.FName='苏州安派思包装有限公司' and FMaterialName like'%"+ shinf + "%'",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FBillNo",
            };
            //调用接口
            var result1 = client1.ExecuteBillQuery(paramed.ToJson());
            //转换成标准文档并遍历
            var dataTable2 = one.DAtaijs();
            var ssjinf = 0;
            var wenjian = 0;
            shulian = shulian == "" ? "0" : shulian;
            foreach (var item in result1)
            {
                ssjinf++;
                if (ssjinf == int.Parse(shulian))
                {
                    dataTable2.Rows.Add(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8]);
                    wenjian++;
                }
                else if (shulian == null || shulian == "0")
                {
                    dataTable2.Rows.Add(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8]);
                }
            }
            //datatable2为返回的发货通知单的列----A
            //使用A 获取所在物料清单中的BOM项

            //List<List<object>> BiaoR = NewMethod();
            //遍历到发货通知单的子项 根据子项去判断物料清单中是否存在 不存返回空 存在返回物料

            //查询物料列表 条件为 编码为12.99.20 的物料 且GM不为空
            DataTable ji = dataTable2.Copy();
            DataRow[] selectedRows = dataTable2.Select("FMaterial like '12.99.20%'");
            if (selectedRows.Length > 0)
            {
                for (int l = 0; l < selectedRows.Length; l++)
                {
                    var JISN = selectedRows[l][2];
                    ji.Rows.Add("", "", selectedRows[l][2], "", "", "", "");///暂存获取到的子项物料-------获取到的物料
                }
            }
            else
            {
                if (result1 != null)
                {
                    for (int i = 0; i < wenjian; i++)
                    {
                        //业务对象标识
                        string formId2 = "ENG_BOM";
                        //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
                        string fieldKeys2 = "FMATERIALIDCHILD.FNumber";
                        //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                        DataRow fro = dataTable2.Rows[i];
                        var FL = fro[2];
                        var FLSD = Convert.ToString(fro["FSaleO"]);
                        var Para = new QueryParam()
                        {
                            FormId = formId2,
                            FieldKeys = fieldKeys2,
                            FilterString = "FMATERIALID.FNumber like'%" + FL + "%'and FUseOrgId.FName='" + FLSD + "'",
                            TopRowCount = 0,
                            StartRow = 0,
                            Limit = 120,
                        };
                        //调用接口
                        var result2 = client1.ExecuteBillQuery(Para.ToJson());//返回的是物料清单的一级物料名称
                                                                              //遍历一级物料查找其中有无符合BiaoR的字段


                        for (int j = 0; j < result2.Count; j++)
                        {
                            dataTable2.Rows.Add("", "", result2[j][0].ToString(), "", "", "");
                            //业务对象标识
                            string formId3 = "ENG_BOM";
                            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
                            string fieldKeys3 = "FMATERIALIDCHILD.FNumber";
                            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                            var Bfro = result2[j][0];
                            var Paraed = new QueryParam()
                            {
                                FormId = formId3,
                                FieldKeys = fieldKeys3,
                                FilterString = "FMATERIALID.FNumber like'" + Bfro + "%'and  FUseOrgId.FName='" + FLSD + "'",
                                TopRowCount = 0,
                                StartRow = 0,
                                Limit = 120,
                            };
                            //调用接口
                            var resulted = client1.ExecuteBillQuery(Paraed.ToJson());

                            for (int l = 0; l < resulted.Count; l++)
                            {
                                var shunf = resulted[l][0].ToString();
                                dataTable2.Rows.Add("", "", resulted[l][0].ToString(), "", "", "");
                            }
                        }
                    }
                    //遍历datatable 
                    ji.Rows.Clear();
                    ji.ImportRow(dataTable2.Rows[0]);
                    DataRow[] selectedRowsdd = dataTable2.Select("FMaterial like '12.99.20%'");
                    for (int l = 0; l < selectedRowsdd.Length; l++)
                    {
                        var JISN = selectedRowsdd[l][2];
                        ji.Rows.Add("", "", selectedRowsdd[l][2], "", "", "", "");///暂存获取到的子项物料-------获取到的物料
                    }
                }
            }

            return ji;
        }

        private static List<List<object>> NewMethod()
        {
            //.////遍历发货通知单 获取当前要打印的发货通知单的行信息
            //物料列表查询物料
            K3CloudApi Biaoqina = new K3CloudApi();
            //业务对象标识
            string BianB = "BD_MATERIAL";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string BiaoF = "FNumber";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式 bianma--物料编码
            var BIaoP = new QueryParam()
            {
                FormId = BianB,
                FieldKeys = BiaoF,
                FilterString = "FOldNumber IN ('2.16.00100', '2.16.00110')",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 3,
            };
            //调用接口
            var BiaoR = Biaoqina.ExecuteBillQuery(BIaoP.ToJson());//返回标签物料
            return BiaoR;
        }

        //物料查询
        private static DataTable Wuliaos(DataTable da)//shu==时间  shiji==使用组织
        {
            Class1 one = new Class1();

            DataTable jkm = one.Wuliao();
            var fe = da.Rows[0];
            var limk = fe[8].ToString();

            //处理时间中
            var shun = fe[7].ToString();
            shun = shun == "" ? DateTime.Now.ToString("yyyy/M/dd H:M:ss") : shun;
            DateTime date = DateTime.ParseExact(shun, "yyyy/M/dd H:M:ss", CultureInfo.InvariantCulture);

            // 假设的转换规则：年份的后两位 * 10000 + 月份 * 100 + 日期  
            string customNumber = (date.Year % 100).ToString() + date.Month.ToString()  + date.Day.ToString();

            for (int i = 1; i < da.Rows.Count; i++)
            {
                DataRow de = da.Rows[i];
                K3CloudApi client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_MATERIAL";
                //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
                string fieldKeys = "F_SMGS_GM_NUMBER,F_SMGS_ACD_NUMBER,F_SMGS_PACKAGE_QTY,F_SMGS_SOURCE_CODE,F_SMGS_PARTNAME_SPA,F_SMGS_PARTNAME_FRE,F_SMGS_PARTNAME_EN,F_SMGS_UPC,F_SMGS_COUNTRY_OF_ORIGIN3,F_SMGS_LINE_CODE,F_SMGS_GROUPNUMBER,F_SMGS_COUNTRY_OF_ORIGIN2,F_SMGS_COUNTRY_OF_ORIGIN1,F_SMGS_CORE_GROUP,FOldNumber";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式 bianma--物料编码
                var bain = de[2];
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = "FNumber='" + bain + "' and FUseOrgId.FName='" + limk + "'",
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 120,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());

                foreach (var item in result)
                {
                    jkm.Rows.Add(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8], item[9], item[10], item[11], item[12], item[13], customNumber, "", item[14]);
                }
            }
            return jkm;
        }
        //
        private static string biaoqinazhi(DataTable dataTable2, string FE, string FES, string path)
        {
            for (int i = 1; i < dataTable2.Rows.Count; i++)
            {
                DataRow dr = dataTable2.Rows[i];
                DataRow drs = dataTable2.Rows[0];
                //根据单号查找物料并返回
                K3CloudApi client1 = new K3CloudApi();
                //业务对象标识
                string formId1 = "ENG_BOM";
                //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
                string fieldKeys1 = "FMATERIALIDCHILD.FNumber";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var ZBLxsx = dr[2];
                var FLSD = drs[8];
                var paramed = new QueryParam()
                {
                    FormId = formId1,
                    FieldKeys = fieldKeys1,
                    FilterString = "FMATERIALID.FNumber like'" + ZBLxsx + "%' and FUseOrgId.FName='苏州安派思包装有限公司'",
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 120
                };
                //调用接口
                var result1 = client1.ExecuteBillQuery(paramed.ToJson());
                for (int iu = 0; iu < result1.Count; iu++)
                {
                    if (result1[iu][0].ToString() == FE)
                    {
                        path = "~/Fastreport/ProductBoxB.frx";
                    }
                    if (result1[iu][0].ToString() == FES)
                    {
                        path = "~/Fastreport/ProductBoxA.frx";
                    }
                }
            }

            return path;
        }
    }
}